package com.orderplus.opshop.core.proxy;

import com.orderplus.opshop.common.util.GsonUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class ProxyUtil {

	//解析网页数据，获取ip和端口信息
	public static List<ProxyIpInfo> requestUrl(int index) {
		String url = "http://www.xicidaili.com/nt/" + index;
		List<ProxyIpInfo> list = new ArrayList<ProxyIpInfo>();
		try {
			Document document = Jsoup.connect(url).get();
			Elements elements = document.getElementById("ip_list").select("tr");
			for (Element element : elements) {
				if (!element.children().get(1).html().contains("IP地址")) {
					ProxyIpInfo ipInfo = new ProxyIpInfo();
					ipInfo.setIp(element.children().get(1).html());
					ipInfo.setPort(element.children().get(2).html());
					ipInfo.setType(element.children().get(5).html());
					list.add(ipInfo);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	// 过滤有效的ip信息
	public static List<ProxyIpInfo> parseProxyIpList(List<ProxyIpInfo> ipInfos) {
		List<ProxyIpInfo> infoList = new ArrayList<ProxyIpInfo>();
		for (ProxyIpInfo info : ipInfos) {
			if (validateIp(info)) {
				System.out.println(GsonUtil.toString(info));

				infoList.add(info);
//				save(info);
			} else {
				System.out.println("无效");
			}
		}
		return infoList;
	}

//	private static String defaultUrl = "http://ip.chinaz.com/getip.aspx";
	private static String defaultUrl = "https://www.baidu.com/";


	private static boolean validateIp(ProxyIpInfo ipInfo) {
		return  validateIp(ipInfo,defaultUrl);
	}
	// 验证ip是否有效
	private static boolean validateIp(ProxyIpInfo ipInfo,String urlStr) {
		try {
			proxyConnect( urlStr, ipInfo);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static URLConnection proxyConnect(String href, ProxyIpInfo ipInfo) throws IOException {
		URL url = new URL(href);
		InetSocketAddress addr = new InetSocketAddress(ipInfo.getIp(), Integer.parseInt(ipInfo.getPort()));
		// http 代理
		Proxy proxy = new Proxy(Proxy.Type.HTTP	, addr);
		URLConnection conn = url.openConnection(proxy);
		conn.setConnectTimeout(5000);
		conn.connect();
		return conn;
	}

	public static String proxyHtml(URLConnection connection) throws IOException {
		InputStream is = connection.getInputStream();

		BufferedReader buffer = new BufferedReader(new InputStreamReader(is));

		StringBuffer bs = new StringBuffer();

		String l = null;

		while((l=buffer.readLine())!=null){

			bs.append(l);

		}
		return bs.toString();
	}

	// 获取可用的代理ip列表
	public static void getProxyIp() {
		int startPage = 1, endPage = 2;
		for (; startPage <= endPage; startPage++) {
			List<ProxyIpInfo> list = requestUrl(startPage);
			List<ProxyIpInfo> use = parseProxyIpList(list);
		}
	}

	public static void testConnect() {
		try {
//			ProxyIpInfo proxyIpInfo = new ProxyIpInfo();
//			proxyIpInfo.setIp("27.46.34.49");
//			proxyIpInfo.setPort("9797");
//			proxyIpInfo.setType("HTTP");


			List<ProxyIpInfo> list = requestUrl(1);
			List<ProxyIpInfo> use = parseProxyIpList(list);
			for(ProxyIpInfo proxyIpInfo : use) {
				URLConnection connection = proxyConnect(defaultUrl, proxyIpInfo);
				String html = proxyHtml(connection);
				Document doc = Jsoup.parse(html);

				System.out.println(doc.select("body").toString());
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void save(ProxyIpInfo info) {
		String sql = "INSERT INTO proxy_ip_list (ip, port, type) VALUES('" + info.getIp() + "','" + info.getPort() + "','" + info.getType() + "')";
		SQLiteJDBC.INSERT(sql);
	}

	public static void main(String[] args) {
//		getProxyIp();
		testConnect();
	}
}
